<?php
class Shoppingcart_Models_Dao_Pdo_Mysql_Cart extends Tomato_Model_Dao
    implements Shoppingcart_Models_Interface_Cart
{
    public function convert($entity)
    {
        return new Shoppingcart_Models_Cart($entity);
    }

    public function getCart($exp = null){
        $select = $this->_conn
                        ->select()
                        ->from(array('c' => $this->_prefix.'shopping_cart'), array('cart_id'))
                        ;
        $rowset = $select->query()->fetchAll();
        return new Tomato_Model_Recordset($rowset, $this);
    }

    public function getLastId(){
        $select = $this->_conn
                        ->select()
                        ->from(array('c' => $this->_prefix.'shopping_cart'), array('cart_id'))
                        ->limit(1)
                        ->order('c.cart_id DESC')
                        ;
        $rowset = $select->query()->fetchAll();
        $cart = new Tomato_Model_Recordset($rowset, $this);
        return (count($cart) == 0) ? 0 : $cart[0]->cart_id;
    }

    public function getById($id){
        $row = $this->_conn
                    ->select()
                    ->from(array('c' => $this->_prefix . 'shopping_cart'))
                    ->where('c.cart_id = ?', $id)
                    ->limit(1)
                    ->query()
                    ->fetch();
        return (null == $row) ? null : new Shoppingcart_Models_Cart($row);
    }
    
    /**
     * Get cart detail by product id
     *
     * @since 29-04-2011
     * @author quanvo
     * @param int $id
     * @return Tomato_Model_Recordset
     */
    public function getByProId($id){
        $row = $this->_conn
                    ->select()
                    ->from(array('c' => $this->_prefix . 'shopping_cart'))
                    ->where('c.product_id = ?', $id)
                    ->limit(1)
                    ->query()
                    ->fetch();
        return (null == $row) ? null : new Shoppingcart_Models_Cart($row);
    }

    public function getDetailById($id, $product_id = null){
        $select = $this->_conn
                        ->select()
                        ->from(array('cd' => $this->_prefix.'shopping_cart_detail'))
                        ->where('cd.cart_id = ?', $id)
                        ->order('cd.id ASC');
		if($product_id){
			$select->where('cd.product_id = ?', $product_id);
		}
        $rowset = $select->query()->fetchAll();
        return new Tomato_Model_Recordset($rowset, $this);
    }

    public function add($cart){
        return $this->_conn->insert($this->_prefix . 'shopping_cart',
                            array(
                                'cart_id'      => $cart->cart_id,
                                'created_date' => $cart->created_date,
                            ));
    }

    public function addDetail($cart){
        $this->_conn->insert($this->_prefix . 'shopping_cart_detail',
                            array(
                                'cart_id'                          => $cart->cart_id,
                                'product_id'                       => $cart->product_id,
                                'cart_quantity'                    => $cart->cart_quantity,
                                'product_attribute_value_id_chain' => $cart->product_attribute_value_id_chain,
                                'cart_parent_id'                   => $cart->cart_parent_id,
                            ));
        $lastId = $this->_conn->lastInsertId($this->_prefix . 'shopping_cart_detail');

        /**
         * Check $lastId larger limit allowed
        **/
        if($lastId > 4200000000){
            $this->resetAutoIncrement();
        }
        return $lastId;
    }

    public function update($cart){
        $where[] = "cart_id = {$cart->cart_id}";
        return $this->_conn->update($this->_prefix . 'shopping_cart',
                            array(
                                'created_date' => $cart->created_date,
                            ), $where);
    }

    public function updateDetail($cart){
        $where[] = "id = {$cart->id}";
        return $this->_conn->update($this->_prefix . 'shopping_cart_detail',
                            array(
                                'product_attribute_value_id_chain' => $cart->product_attribute_value_id_chain,
                            ), $where);
    }

    public function updateQuantiy($cart){
        $where[] = "id = {$cart->id}";
        return $this->_conn->update($this->_prefix . 'shopping_cart_detail',
                            array(
                                'cart_quantity' => $cart->cart_quantity,
                            ), $where);
    }

    public function delete($id){
        $where[] = 'cart_id = '.$this->_conn->quote($id);
        $this->_conn->delete($this->_prefix.'shopping_cart_detail', $where);
        return $this->_conn->delete($this->_prefix.'shopping_cart', $where);
    }

    public function deleteDetail($id){
        $where[] = 'id = '.$this->_conn->quote($id).' OR cart_parent_id = '.$this->_conn->quote($id);
        return $this->_conn->delete($this->_prefix.'shopping_cart_detail', $where);
    }

    public function getProductById($id){
        $select = $this->_conn
                        ->select()
                        ->from(array('p' => $this->_prefix.'shop_product'))
                        ->joinLeft(array('pc' => $this->_prefix.'shop_product_content'), "p.product_id = pc.product_id AND pc.language_code = '{$this->_lang}'", array('product_content_id', 'language_code', 'product_content_name', 'slug'=>'product_content_friendly_url', 'product_content_description'))
                        ->limit(1)
                        ->where('p.product_id = ?', $id)
                        ;
        $rowset = $select->query()->fetchAll();
        $products = new Tomato_Model_Recordset($rowset, $this);
        return (count($products) == 0) ? 0 : $products[0];
    }

    public function checkFile($path, $file, $name = '_square'){
        $new_file = null;
        if(is_file($path)){
            $pathinfo = pathinfo($path);
            $arrEx = explode('_',$file);
            $forReplace = $arrEx[count($arrEx)-1];
            $new_file = str_replace('_'.$forReplace, $name.'.'.$pathinfo['extension'], $file);
        }
        return $new_file;
    }

    public function resetAutoIncrement(){
        $sql = "alter table `shopping_cart_detail` auto_increment=1 comment='' row_format=dynamic";
        $void = $this->_conn->query($sql);
    }

    public function getCDById($id){
        $row = $this->_conn
                    ->select()
                    ->from(array('cd' => $this->_prefix . 'shopping_cart_detail'))
                    ->where('cd.id = ?', $id)
                    ->limit(1)
                    ->query()
                    ->fetch();
        return (null == $row) ? null : new Shoppingcart_Models_Cart($row);
    }

    public function getCBD($date){
        $select = $this->_conn
                        ->select()
                        ->from(array('c' => $this->_prefix.'shopping_cart'))
                        ->where("c.created_date < '{$date}'")
                        ;
        $rowset = $select->query()->fetchAll();
        return new Tomato_Model_Recordset($rowset, $this);
    }
    
    public function sumQty($cart_id, $product_id){
        $select = $this->_conn
                        ->select()
                        ->from(array('cd' => $this->_prefix.'shopping_cart_detail'), array('sum' => 'sum(cart_quantity)'))
                        ->where("cd.cart_id = ?", $cart_id)
                        ->where("cd.product_id = ?", $product_id)
                        ;                        
        $row = $select->query()->fetch();
        return $row->sum;
    }
}
